﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KalevaAalto.CollectionPart
{
    public class LazyAsyncCollection
    {
        private IDictionary<string,LazyAsync<object?>> _dic = new Dictionary<string,LazyAsync<object?>>();



        public LazyAsyncCollection() { }



        public LazyAsyncCollection Add(string key,object? value)
        {
            var lazy = new LazyAsync<object?>(async () => value);
            _dic.Add(key, lazy);
            return this;
        }

        public LazyAsyncCollection Add(string key, Func<object?> func)
        {
            var lazy = new LazyAsync<object?>(async () => func());
            _dic.Add(key,lazy);
            return this;
        }

        public LazyAsyncCollection Add(string key, Func<Task<object?>> func)
        {
            var lazy = new LazyAsync<object?>(func);
            _dic.Add(key, lazy);
            return this;
        }

        public LazyAsyncCollection Add(string key, Func<LazyAsyncCollection ,object?> func)
        {
            var lazy = new LazyAsync<object?>(async () => func(this));
            _dic.Add(key, lazy);
            return this;
        }

        public LazyAsyncCollection Add(string key, Func<LazyAsyncCollection,Task<object?>> func)
        {
            var lazy = new LazyAsync<object?>(async ()=> await func(this));
            _dic.Add(key, lazy);
            return this;
        }





        public async Task<T?> GetValueAsync<T>(string key)
        {
            if (!_dic.ContainsKey(key))
            {
                return default(T);
            }

            var lazy = _dic[key];
            var value = await lazy.GeteValueAsync();
            if(value is T)
            {
                return (T)value;
            }
            else
            {
                return default(T);
            }
        }

        public async Task<T> GetValueUnCheckAsync<T>(string key)
        {
            var value = await GetValueAsync<T>(key);
            return value!;
        }


        public LazyAsyncCollection Clear()
        {
            _dic.Clear();
            return this;
        }



    }
}
